<template>
  <div>
    <div class="user-area">
      <v-viewer ref="view"></v-viewer>
      <div v-if="isInfo && userInfo.label && userInfo.label == 1"
           class="top-area">
        <el-row>
          <el-button @click="() => {this.$router.go(-1)}"
                     size="small"
                     type="primary">返回</el-button>
        </el-row>
      </div>
      <div class="title">
        <div class="point"></div>
        <span>用户资料</span>
      </div>
      <el-row :gutter="10">
        <el-col :span="3">
          <div class="content-title">
            <span>公司名称</span>
          </div>
        </el-col>
        <el-col :span="9">
          <span>{{ userInfo.companyName }}</span>
        </el-col>
        <el-col :span="3">
          <div class="content-title">
            <span>手机号</span>
          </div>
        </el-col>
        <el-col :span="9">
          <span>{{ userInfo.phone }}</span>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="3">
          <div class="content-title">
            <span>用户名称</span>
          </div>
        </el-col>
        <el-col :span="9">
          <span>{{ userInfo.userName }}</span>
        </el-col>
        <el-col :span="3">
          <div class="content-title">
            <span>用户属性</span>
          </div>
        </el-col>
        <el-col :span="9">
          <span v-if="userInfo.label === 1">大客户</span>
          <span v-if="!userInfo.label">普通客户</span>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="3">
          <div class="content-title">
            <span>门头/办公场所</span>
          </div>
        </el-col>
        <el-col :span="9">
          <div>
            <pic-view :pic-url-list.sync="userInfo.companyImgList"
                      upload-class="lang-upload"
                      :pic-name-list.sync="userInfo.companyNameList"
                      :upload-data="{ picName: 'user/' + userId }"
                      :max-size="1"
                      :upload-type="isInfo"
                      @showImg="showImg"></pic-view>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="content-title">
            <span>名片</span>
          </div>
        </el-col>
        <el-col :span="9">
          <div>
            <pic-view :pic-url-list.sync="userInfo.businessCardImgList"
                      upload-class="lang-upload"
                      :pic-name-list.sync="userInfo.businessCardNameList"
                      :upload-data="{ picName: 'user/' + userId }"
                      :max-size="1"
                      :upload-type="isInfo"
                      @showImg="showImg"></pic-view>
          </div>
        </el-col>
      </el-row>
      <template v-if="isInfo && userInfo.label && userInfo.label == 1">
        <div class="title">
          <div class="point"></div>
          <span>关联产品</span>
        </div>
        <el-form size="medium"
                 label-position="right"
                 label-width="100px">
          <el-form-item label="金融方案"
                        required>
            <el-col :span="3">
              <el-button @click="openProductDialog"
                         size="small"
                         type="primary"
                         plain>添加方案</el-button>
            </el-col>
            <el-col :span="8"
                    :push="12">
              <el-tabs v-model="activeName"
                       @tab-click="changeProductType">
                <el-tab-pane label="全部"
                             name="0"></el-tab-pane>
                <el-tab-pane label="新车"
                             name="1"></el-tab-pane>
                <el-tab-pane label="二手车"
                             name="2"></el-tab-pane>
                <el-tab-pane label="以租代购"
                             name="3"></el-tab-pane>
              </el-tabs>
            </el-col>
          </el-form-item>
        </el-form>
        <div class="table-area">
          <el-table border
                    stripe
                    :data="productList"
                    tooltip-effect="dark"
                    style="width: 100%">
            <el-table-column prop="productName"
                             label="方案名称"></el-table-column>
            <el-table-column label="最低首付比例">
              <template slot-scope="scope">
                <span v-if="scope.row.downpayRatio">{{scope.row.downpayRatio}}%</span>
                <span v-else>无</span>
              </template>
            </el-table-column>
            <el-table-column label="贷款额度区间">
              <template slot-scope="scope">
                <span v-if="scope.row.loanLower && scope.row.loanUpper">{{scope.row.loanLower}}~{{scope.row.loanUpper}}</span>
                <span v-else>无</span>
              </template>
            </el-table-column>
            <el-table-column label="利率(%)">
              <template slot-scope="scope">
                <span v-if="scope.row.interestRate">{{scope.row.interestRate}}</span>
                <span v-else>无</span>
              </template>
            </el-table-column>
            <el-table-column width="70"
                             prop="period"
                             label="总期数"></el-table-column>
            <el-table-column label="业务类型">
              <template slot-scope="scope">
                <span v-if="scope.row.businessType === 1">新车</span>
                <span v-if="scope.row.businessType === 2">二手车</span>
                <span v-if="scope.row.businessType === 3">以租代购现车</span>
              </template>
            </el-table-column>
            <el-table-column prop="cityName"
                             label="区域"></el-table-column>
            <el-table-column label="操作"
                             width="300">
              <template slot-scope="scope">
                <el-button v-if="scope.row.status == 0"
                           @click="undercarriage(scope.row.productId)"
                           style="margin-left: 10px;"
                           type="danger"
                           size="mini"
                           plain>下架</el-button>
                <template v-else>
                  <el-button @click="upcarriage(scope.row.productId)"
                             style="margin-left: 10px;"
                             type="success"
                             size="mini"
                             plain>上架</el-button>
                  <el-button @click="modify(scope.row.productId, scope.row.businessType)"
                             type="primary"
                             size="mini"
                             plain>修改</el-button>
                </template>
                <el-button @click="gotoDetail(scope.row.productId, scope.row.businessType)"
                           type="primary"
                           size="mini"
                           plain>详情</el-button>
                <el-button @click="deleteProduct(scope.row.productId)"
                           class="cell-delete"
                           type="text"
                           icon="el-icon-delete"
                           circle></el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="table-foot">
          </div>
        </div>
        <view-page :current-page="productPage"
                   :total="productTotal"
                   @change="productPageChange"></view-page>
        <div class="user-area">
          <div class="title">
            <div class="point"></div>
            <span>关联车型</span>
          </div>
          <el-form size="medium"
                   label-position="right"
                   label-width="100px">
            <el-form-item label="车型"
                          required>
              <el-col>
                <el-col :span="3">
                  <el-button @click="() => carDialog = true"
                             size="small"
                             type="primary"
                             plain>设置车型</el-button>
                </el-col>
                <el-col>
                  <span style="color:grey">未找到需要的车型，</span>
                  <el-button type="text"
                             @click="() => addCarDialog=true">点击新增</el-button>
                </el-col>
              </el-col>
            </el-form-item>
          </el-form>
          <div class="table-area">
            <el-table border
                      stripe
                      :data="carList"
                      tooltip-effect="dark"
                      style="width: 100%">
              <el-table-column prop="brandName"
                               label="汽车品牌"></el-table-column>
              <el-table-column prop="seriesName"
                               label="车系"></el-table-column>
              <el-table-column prop="modelName"
                               label="车型"></el-table-column>
              <el-table-column prop="colors"
                               label="颜色"></el-table-column>
              <el-table-column label="操作"
                               width="300">
                <template slot-scope="scope">
                  <el-button @click="modifyUserCar(scope.row)"
                             type="primary"
                             size="mini"
                             plain>修改</el-button>
                  <el-button @click="deleteUserCar(scope.row.relateId)"
                             class="cell-delete"
                             type="text"
                             icon="el-icon-delete"
                             circle></el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="table-foot">
            </div>
          </div>
          <view-page :current-page="carPage"
                     :total="carTotal"
                     @change="carPageChange"></view-page>
        </div>
      </template>
    </div>
    <div v-if="!isInfo"
         class="foot">
      <el-button @click="approve(2)"
                 type="primary">通过</el-button>
      <el-button @click="approve(3)"
                 type="danger">不通过</el-button>
      <el-button @click="() => {this.$router.go(-1)}"
                 type="primary">取消</el-button>
    </div>
    <div v-if="isInfo && !userInfo.label"
         class="foot">
      <el-button @click="() => {this.$router.go(-1)}"
                 type="primary">确定</el-button>
    </div>
    <el-dialog title="关联车型"
               :visible.sync="carDialog">
      <div class="user-area">
        <car-cascade :checked-car.sync="checkedCar"
                     :modify-car.sync="modifyCar"></car-cascade>
      </div>
      <div class="foot">
        <el-button @click="relateCar()"
                   type="primary"
                   plain>确认添加</el-button>
        <el-button @click="carDialog = false"
                   plain>取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="关联产品"
               :visible.sync="productDialog">
      <div class="user-area">
        <el-tabs type="border-card"
                 @tab-click="changeProduct"
                 v-model="productTabsIndex">
          <el-tab-pane v-for="(item, index) in productTabs"
                       :key="index"
                       :label="item.label"
                       :name="item.name">
            <el-table ref="multipleTable"
                      :data="allProductList"
                      border
                      stripe
                      tooltip-effect="dark"
                      style="width: 100%"
                      max-height="450"
                      @selection-change="handleSelectionChange">
              <el-table-column type="selection"
                               width="55"></el-table-column>
              <el-table-column prop="productName"
                               label="方案名称"></el-table-column>
              <el-table-column prop="downpayRatio"
                               label="最低首付比例"></el-table-column>
              <el-table-column prop="loanInterval"
                               label="贷款额度区间"></el-table-column>
              <el-table-column prop="interestRate"
                               label="利率(%)"></el-table-column>
              <el-table-column width="70"
                               prop="period"
                               label="总期数"></el-table-column>
              <el-table-column prop="cityName"
                               label="区域"></el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="foot">
        <el-button @click="relate()"
                   type="primary"
                   plain>确认添加</el-button>
        <el-button @click="productDialog = false"
                   plain>取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="新增车型"
               :visible.sync="addCarDialog">
      <div>
        <el-form size="medium"
                 label-position="right"
                 label-width="200px">
          <el-form-item label="品牌">
            <el-col :span="7">
              <el-form-item>
                <el-input v-model="carInfo.brandName"
                          size="medium"></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="车系">
            <el-col :span="7">
              <el-form-item>
                <el-input v-model="carInfo.seriesName"
                          size="medium"></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="车型">
            <el-col :span="7">
              <el-form-item>
                <el-input v-model="carInfo.modelName"
                          size="medium"></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="车辆指导价">
            <el-col :span="7">
              <el-form-item>
                <el-input v-model.number="carInfo.price"
                          size="medium"></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="车型年限">
            <el-col :span="7">
              <el-form-item>
                <el-input v-model="carInfo.modelYear"
                          size="medium"></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="车辆颜色">
            <el-col :span="7">
              <el-form-item>
                <el-input v-model="carInfo.carColor"
                          size="medium"></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
        </el-form>
      </div>
      <div class="foot">
        <el-button @click="addCar"
                   type="primary">新增</el-button>
        <el-button @click="addCarDialog = false"
                   plain>取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.el-form-item {
  margin-bottom: 0px;
}
.top-area {
  padding: 10px 5px;
}
.table-area {
  padding: 10px 20px 10px 20px;
}
.el-dialog {
  width: 80%;
}
.el-dialog__header {
  background-color: #409eff;
  & > .el-dialog__title {
    color: #fff;
    font-size: 20px;
    padding-left: 40px;
  }
}
</style>

<script>
import '@/style/info.scss'
import '@/style/common.scss'
import picView from '@/components/pic-viewer-up'
import vViewer from '@/components/v-viewer'
import viewPage from '@/components/pagination'
import carCascade from '@/components/car-cascade'
import { api } from '@/api'
import { packageImgList } from '@/utils/imgPackage'
import { HTTPSUCCESS, HTTPDATAFAIL, HTTPPARAMFAIL, HTTPUNKOWNFAIL } from '@/components/constant'
import { validatenull, validateNumber } from '@/utils/validate'

export default {
  data() {
    return {
      activeName: '0',
      productDialog: false,
      carDialog: false,
      addCarDialog: false,
      productPage: 1,
      productTotal: 1,
      carPage: 1,
      carTotal: 1,
      isInfo: this.infoFlag === '1',
      productTabsIndex: '1',
      productTabs: [],
      productList: [],
      carList: [],
      allProductList: [],
      checkedCar: {},
      modifyCar: {},
      carInfo: {
        brandName: null,
        seriesName: null,
        modelName: null,
        price: null,
        modelYear: null,
        carColor: null
      },
      userInfo: {
        companyImgList: [],
        companyNameList: [],
        businessCardImgList: [],
        businessCardNameList: []
      }
    }
  },
  components: {
    picView, vViewer, viewPage, carCascade
  },
  props: [
    'userId', 'infoFlag'
  ],
  computed: {
  },
  activated() {
    this.getUserDetail()
    this.getProductTabs()
    this.getProductList()
    this.getCarList()
  },
  methods: {
    modifyUserCar(modifier) {
      this.modifyCar = modifier
      this.carDialog = true
    },
    addCar() {
      if (validatenull(this.carInfo.brandName)) return this.$msg._message('请输入品牌', 'warning')
      if (validatenull(this.carInfo.seriesName)) return this.$msg._message('请输入车系', 'warning')
      if (validatenull(this.carInfo.modelName)) return this.$msg._message('请输入车型', 'warning')
      if (validatenull(this.carInfo.price)) return this.$msg._message('请输入车辆指导价', 'warning')
      if (validatenull(this.carInfo.carColor)) return this.$msg._message('请输入车辆颜色', 'warning')
      if (!validateNumber(this.carInfo.price)) return this.$msg._message('车辆指导价必须为数字', 'warning')
      const params = {
        brandName: this.carInfo.brandName,
        seriesName: this.carInfo.seriesName,
        modelName: this.carInfo.modelName,
        price: this.carInfo.price,
        color: this.carInfo.carColor,
        modelYear: this.carInfo.modelYear
      }
      this.$http.post(api.SYS_CAR_ADD, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.$msg._message('车型新增成功！', 'success')
            this.addCarDialog = false
          } else {
            this.$msg._message('车型新增失败 请联系系统管理员', 'error')
          }
        }
      )
    },
    changeProductType(tab) {
      let type = Number.parseInt(tab.name)
      if (type === 0) type = null
      const params = {
        pageNum: 1,
        pageSize: 10,
        ownerId: this.userId,
        businessType: type
      }
      this.$http.post(api.SYS_PRODUCT_PRODUCTS, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.productList = res.data.loanproductList
            this.productPage = res.data.pageNum
            this.productTotal = res.data.totalSize
          } else {
            this.$msg._message('查询失败 请联系系统管理员', 'error')
          }
        }
      )
    },
    openProductDialog() {
      this.productTabsIndex = '1'
      const params = {
        businessType: this.productTabs[0].type
      }
      this.$http.post(api.SYS_PRODUCT_PRODUCTS_USER, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.allProductList = res.data
            this.productDialog = true
          } else {
            this.$msg._message(res.msg, 'error')
          }
        }
      )
    },
    getProductTabs() {
      if (this.info) {
        this.$http.get(api.SYS_PRODUCT_COUNT_TYPE).then(
          res => {
            if (res.code === HTTPSUCCESS) {
              this.productTabs = res.data
            } else {
              this.$msg._message(res.msg, 'error')
            }
          }
        )
      }
    },
    getUserDetail() {
      this.$http._get(api.SYS_USER_DETAIL, this.userId).then(
        res => {
          this.userInfo = res.data
          if (!validatenull(res.data.userDataId)) {
            const companyList = packageImgList([res.data.company])
            this.userInfo.companyNameList = companyList[0]
            this.userInfo.companyImgList = companyList[1]
            const businessCardList = packageImgList([res.data.businessCard])
            this.userInfo.businessCardNameList = businessCardList[0]
            this.userInfo.businessCardImgList = businessCardList[1]
          }
        }
      )
    },
    getProductList() {
      if (this.info) {
        const params = {
          pageNum: this.productPage,
          pageSize: 10,
          ownerId: this.userId
        }
        this.$http.post(api.SYS_PRODUCT_PRODUCTS, params).then(
          res => {
            if (res.code === HTTPSUCCESS) {
              this.productList = res.data.loanproductList
              this.productPage = res.data.pageNum
              this.productTotal = res.data.totalSize
            } else {
              this.$msg._message('查询失败 请联系系统管理员', 'error')
            }
          }
        )
      }
    },
    getCarList() {
      if (this.info) {
        const params = {
          pageNum: this.carPage,
          pageSize: 10,
          ownerId: this.userId
        }
        this.$http.post(api.SYS_USER_CARS, params).then(
          res => {
            if (res.code === HTTPSUCCESS) {
              this.carList = res.data.userCarList
              this.carPage = res.data.pageNum
              this.carTotal = res.data.totalSize
            } else {
              this.$msg._message('查询失败 请联系系统管理员', 'error')
            }
          }
        )
      }
    },
    approve(authStatus) {
      const params = {
        userId: this.userInfo.userId,
        authStatus: authStatus
      }
      this.$http.post(api.SYS_USER_JUDGE, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.$msg._message('审核成功！', 'success')
            this.$router.push({ name: 'user' })
          } else {
            this.$msg._message(res.msg, 'error')
          }
        }
      )
    },
    undercarriage(id) {
      const params = {
        productIds: [id],
        status: 1
      }
      this.$http.post(api.SYS_PRODUCT_MODIFYSTATUS, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.$msg._message('下架成功', 'success')
            this.getProductList()
          } else {
            this.$msg._message('下架失败 请联系系统管理员', 'error')
          }
        }
      )
    },
    upcarriage(id) {
      const params = {
        productIds: [id],
        status: 0
      }
      this.$http.post(api.SYS_PRODUCT_MODIFYSTATUS, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.$msg._message('上架成功', 'success')
            this.getProductList()
          } else {
            this.$msg._message('上架失败 请联系系统管理员', 'error')
          }
        }
      )
    },
    deleteProduct(id) {
      const params = {
        productIds: [id]
      }
      this.$http.post(api.SYS_PRODUCT_DEL, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.$msg._message('删除产品成功', 'success')
            this.getProductList()
          } else {
            this.$msg._message('删除产品失败 请联系系统管理员', 'error')
          }
        }
      )
    },
    deleteUserCar(id) {
      const params = {
        relateId: id
      }
      this.$http.post(api.SYS_USER_DELETE_CAR, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.$msg._message('删除车型关联成功', 'success')
            this.getCarList()
          } else {
            this.$msg._message('删除车型关联失败 请联系系统管理员', 'error')
          }
        }
      )
    },
    modify(productId, type) {
      let name
      type === 1 ? name = 'modifyUserNewCarProduct' : type === 2 ? name = 'modifyUserSecondCarProduct' : name = 'modifyUserPresentProduct'
      this.$router.push({
        name: name,
        params: {
          productId: productId
        }
      })
    },
    gotoDetail(id, type) {
      let name
      type === 1 ? name = 'userNewCarDetail' : type === 2 ? name = 'userSecondCarDetail' : name = 'userPresentDetail'
      this.$router.push({
        name: name,
        params: {
          productId: id
        }
      })
    },
    relate() {
      const productIds = this.productTabs.flatMap(a => a.selectedList).filter(Boolean).map(a => a.productId)
      const params = {
        userId: this.userInfo.userId,
        productIds: productIds
      }
      this.$http.post(api.SYS_PRODUCT_BIND_USER, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.$msg._message('关联成功！', 'success')
            this.productDialog = false
            this.getUserDetail()
            this.getProductTabs()
            this.getProductList()
          } else {
            this.$msg._message(res.msg, 'error')
          }
        }
      )
    },
    relateCar() {
      if (validatenull(this.checkedCar)) return this.$msg._message('请选择要关联的车', 'warning')
      if (validatenull(this.checkedCar.modelId)) return this.$msg._message('请选择车型', 'warning')
      const params = {
        relateId: this.modifyCar.relateId,
        ownerId: this.userInfo.userId,
        modelId: this.checkedCar.modelId,
        colors: this.checkedCar.colors
      }
      this.$http.post(api.SYS_USER_RELATE_CAR, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.$msg._message('关联成功！', 'success')
            this.carDialog = false
            this.getCarList()
          } else {
            this.$msg._message(res.msg, 'error')
          }
        }
      )
    },
    changeProduct(tab, envent) {
      const params = {
        businessType: this.productTabs[tab.index].type
      }
      this.$http.post(api.SYS_PRODUCT_PRODUCTS_USER, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.allProductList = res.data
            const arr = []
            if (this.productTabs[tab.index].selectedList) {
              this.productTabs[tab.index].selectedList.forEach(a => {
                if (this.allProductList.some(b => b.productId === a.productId)) {
                  arr.push(this.allProductList.filter(b => b.productId === a.productId)[0])
                }
              })
            }
            setTimeout(() => {
              this.toggleSelection(arr, tab.index)
            }, 0)
          } else {
            this.$msg._message(res.msg, 'error')
          }
        }
      )
    },
    handleSelectionChange(val) {
      const index = parseInt(this.productTabsIndex)
      this.productTabs[index - 1].selectedList = val
    },
    toggleSelection(rows, index) {
      if (rows) {
        rows.forEach(a => {
          this.$refs.multipleTable[index].toggleRowSelection(a)
        })
      } else {
        this.$refs.multipleTable[index].clearSelection()
      }
    },
    showImg(url) {
      this.$refs.view.showImg(url)
    },
    productPageChange(page) {
      this.productPage = page
      this.getProductList()
    },
    carPageChange(page) {
      this.carPage = page
      this.getcarList()
    }
  }
}
</script>
